package com.useeinfo.oa.modules.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.AnalysisObjectList;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.dao.EnterpriseDao;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.tools.EnterpriseTools;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.vo.TreeSelectVO;
import com.useeinfo.oa.modules.security.vo.TreeVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2018-12-04
 * @createTime: 16:12:33
 * 企业service
 */
@Service
public class EnterpriseBiz extends CrudBiz<EnterpriseDao, Enterprise> {
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    /**
     * 保存子企业
     *
     * @param enterprise
     * @param parentId
     * @return
     */
    public ResultDto addOrUpdate(Enterprise enterprise, String parentId) {
        Enterprise parent = dao.findModel(StringConverters.null2Long(parentId));
        if (null == enterprise.getId()) {
            enterprise.setCreateDate(new Date());
            enterprise.setSystemUser(systemUserBiz.getLoginUser());
            dao.add(enterprise);
            if (null != parent) {
                enterprise.setParentId(parent.getId());
                enterprise.setParentIds(parent.getParentIds() + enterprise.getId() + ",");
            }
            dao.update(enterprise);
        } else {
            Enterprise enterpriseEdit = dao.findModel(enterprise.getId());
            enterpriseEdit.setCode(enterprise.getCode());
            enterpriseEdit.setEnterpriseName(enterprise.getEnterpriseName());
            dao.update(enterpriseEdit);
        }
        return ResultUtil.success();
    }

    /**
     * admin保存企业信息
     *
     * @param enterprise
     * @param applicationIds
     * @return
     */
    public ResultDto addOrUpdate(Enterprise enterprise, String applicationIds, String parentId) {
        Set<ApplicationModule> applicationModuleSet = new HashSet<>();
        if (!StringConverters.null2String(applicationIds).equals("")) {
            for (String applicationId : applicationIds.split(",")) {
                ApplicationModule applicationModule = applicationModuleBiz.findModel(StringConverters.null2Long(applicationId));
                if (null != applicationModule) {
                    applicationModuleSet.add(applicationModule);
                }
            }
        }

        enterprise.setApplicationModuleSet(applicationModuleSet);
        if (null != enterprise.getId()) {
            Enterprise enterpriseEdit = dao.findModel(enterprise.getId());
            enterpriseEdit.setApplicationModuleSet(enterprise.getApplicationModuleSet());
            enterpriseEdit.setEnterpriseName(enterprise.getEnterpriseName());
            enterpriseEdit.setCode(enterprise.getCode());
            dao.update(enterpriseEdit);
            enterprise = enterpriseEdit;
        } else {
            enterprise.setCreateDate(new Date());
            dao.add(enterprise);
        }

        String parentIds = "";
        Enterprise parent = dao.findModel(StringConverters.null2Long(parentId));
        if (null != parent) {
            parentIds += parent.getParentIds();
            enterprise.setParentId(parent.getId());
            enterprise.setParentIds(parent.getParentIds() + enterprise.getId() + ",");
        }/* else {
            enterprise.setParentId(null);
            enterprise.setParentIds("," + enterprise.getId() + ",");
        }*/
        update(enterprise);
        return ResultUtil.success();
    }


    /**
     * 获取企业--架构的数据信息
     *
     * @param id
     * @return
     */
    public ResultDto getEnterpriseMsg(String id) {
        Enterprise enterprise = dao.findModel(StringConverters.null2Long(id));
        if (null == enterprise) {
            return ResultUtil.error("企业信息不存在");
        } else {
            EnterpriseTools enterpriseTools = new EnterpriseTools();
            enterpriseTools.setId(enterprise.getId().toString());
            enterpriseTools.setName(enterprise.getEnterpriseName());
            enterpriseTools.setPid(null);
            enterpriseTools.setChildrens(getChildEnterprise(enterprise));
            List<EnterpriseTools> enterpriseToolsList = new ArrayList<>();
            enterpriseToolsList.add(enterpriseTools);
            return ResultUtil.success(enterpriseToolsList);
        }
    }

    /**
     * 递归企业的信息
     *
     * @param enterprise
     * @return
     */
    public List<EnterpriseTools> getChildEnterprise(Enterprise enterprise) {
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("parentId", enterprise.getId().toString());
        List<Enterprise> enterpriseList = dao.findList(queryParam);
        List<EnterpriseTools> enterpriseToolsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(enterpriseList)) {
            for (Enterprise enterprise1 : enterpriseList) {
                EnterpriseTools enterpriseTools = new EnterpriseTools();
                enterpriseTools.setId(enterprise1.getId().toString());
                enterpriseTools.setName(enterprise1.getEnterpriseName());
                enterpriseTools.setPid(enterprise.getId().toString());
                enterpriseTools.setChildrens(getChildEnterprise(enterprise1));
                enterpriseToolsList.add(enterpriseTools);
            }
        }
        return enterpriseToolsList;
    }

    /**
     * 删除应用
     *
     * @param enterpriseId
     */
    public void removeApplication(Long enterpriseId) {
        dao.removeApplication(enterpriseId);
    }

    /**
     * 获取应用数据
     *
     * @param sysCode
     * @param enterpriseId
     * @return
     */
    public List getApplication(String sysCode, Long enterpriseId) {
        List<TreeSelectVO> treeSelectVOS = new ArrayList<>();
        if (enterpriseId != null) {
            List objects = dao.getApplication(enterpriseId);
            if (CollectionUtils.isNotEmpty(objects)) {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    treeSelectVOS.add(new TreeSelectVO(sysCode, AnalysisObjectList.getJsonString(j, 0)));
                }
            }
        }
        return treeSelectVOS;
    }

    /**
     * 添加应用
     *
     * @param enterpriseId
     */
    public void addApplication(Long enterpriseId, List<String> applicationData) {
        if (CollectionUtils.isNotEmpty(applicationData)) {
            Enterprise enterprise = findModel(enterpriseId);
            applicationData.forEach(applicationId -> {
                ApplicationModule applicationModule = applicationModuleBiz.findModel(StringConverters.ToLong(applicationId));
                if (applicationModule != null)
                    enterprise.addApplicationModule(applicationModule);
            });
        }
    }

    /**
     * 获取所有企业
     *
     * @return
     */
    public ResultDto getEnterpriseTree(String sysCode) {
        JSONObject data = new JSONObject();
        List<TreeVO> treeVOList = new ArrayList<>();

        QueryParam queryParam=new QueryParam();
        queryParam.getSqlMap().put("magicId","1");
        List<Enterprise> enterprises = this.findList(queryParam);
        if (CollectionUtils.isNotEmpty(enterprises)) {
            enterprises.forEach(enterprise -> {
                if (enterprise != null) {
                    treeVOList.add(new TreeVO(enterprise.getEnterpriseName(), "0",
                            enterprise.getId() + "", enterprise.getEnterpriseName(), "enterprises"));
                }
            });
        }
        JSONObject menuMap = new JSONObject();
        menuMap.put(sysCode, treeVOList);
        data.put("menuMap", menuMap);

        //选中项
        data.put("roleMenuList", new JSONArray());
        return ResultUtil.success(data);
    }

    /**
     * 添加企业管理者或超级管理员
     * @param enterpriseId
     * @param systemUser
     * @return
     */
    public ResultDto addSysUserEnterprise(String enterpriseId, SystemUser systemUser) {
        Enterprise enterprise = dao.findModel(StringConverters.null2Long(enterpriseId));
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误，请确认");
        }
        if (null == systemUser.getId()) {
            systemUser.setCreateDate(new Date());
            if(enterprise.getId()==1){//平台管理者
                systemUser.setOperationRole("admin");
            }else {//企业管理者
                systemUser.setOperationRole("enterprise");
            }
            systemUserBiz.save(systemUser);
        } else {

            SystemUser user = systemUserBiz.findModel(systemUser.getId());
            if(enterprise.getId()==1&&!StringConverters.null2String(user.getOperationRole()).equals("admin")){
                return ResultUtil.error("账号为："+user.getUserAccount()+"的用户不是平台级用户，请确认");
            }else if(enterprise.getId()!=1&&!StringConverters.null2String(user.getOperationRole()).equals("enterprise")){
                return ResultUtil.error("账号为："+user.getUserAccount()+"的用户不是企业级用户，请确认");
            }
            user.setUserPassword(systemUser.getUserPassword());
            systemUserBiz.addOrUpdate(user);
            systemUser = user;
        }
        Set<Enterprise> enterpriseSet = systemUser.getEnterpriseSet();
        enterpriseSet.add(enterprise);
        systemUser.setEnterpriseSet(enterpriseSet);


        systemUserBiz.update(systemUser);
        return ResultUtil.success();
    }

    /**
     * 查询总企业数（包括自己）
     * @param enterpriseId
     * @return
     */
    public int childrenCount(String enterpriseId,String beforeCreateDate) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("ancientId",enterpriseId);
        if(StringUtils.isNotBlank(beforeCreateDate)){
            queryParam.getSqlMap().put("beforeCreateDate",beforeCreateDate);
        }
        Long totalEnterpriseCount = this.totalRecord(queryParam.getSqlMap());
        if(totalEnterpriseCount!=null){
            return totalEnterpriseCount.intValue();
        }else{
            return 0;
        }
    }

    /**
     * 查询总企业List（包括自己）
     * @param enterpriseId
     * @return
     */
    public List<Long> childrenList(String enterpriseId) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("ancientId",enterpriseId);
        List<Enterprise> enterpriseList = this.findList(queryParam);
        List<Long> childrenList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(enterpriseList)){
            for(Enterprise enterprise : enterpriseList){
                childrenList.add(enterprise.getId());
            }
        }
        return childrenList;
    }

    /**
     * 查询总企业ID的字符串,逗号隔开（包括自己）
     * @param enterpriseId
     * @return
     */
    public String childrenIds(String enterpriseId) {
        if(StringUtils.isBlank(enterpriseId)){
            return "";
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("ancientId",enterpriseId);
        List<Enterprise> enterpriseList = this.findList(queryParam);
        String ids = "";
        if(CollectionUtils.isNotEmpty(enterpriseList)){
            for(Enterprise enterprise : enterpriseList){
                ids += enterprise.getId()+",";
            }
        }
        if(ids.endsWith(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        return ids;
    }
}
